import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import emitter from '#/utils/events';

export function EchartsComp({ config = {}, getRef = () => {} }) {
  let chartInstance = null;
  const chartRef = useRef(null);
  const resizeHelper = () => {
    setTimeout(() => {
      chartInstance?.resize();
    }, 500);
  };
  useEffect(() => {
    renderChart();
  }, [JSON.stringify(config)]);

  useEffect(() => {
    mounted();
    return () => {
      destoryed();
    };
  }, []);

  function destoryed() {
    chartInstance?.dispose();
    window.removeEventListener('resize', resizeHelper);
    emitter.removeListener('onChangeMnue', resizeHelper);
  }

  function mounted() {
    window.addEventListener('resize', resizeHelper);
    emitter.addListener('onChangeMnue', resizeHelper);
    getRef(chartInstance);
  }
  //鼠标移入横坐标显示省略的全部内容
  function extension(chart) {
    var elementDiv = document.getElementById('extension');
    if (!elementDiv) {
      var div = document.createElement('div');
      div.setAttribute('id', 'extension');
      div.style.display = 'block';
      document.querySelector('html').appendChild(div);
    }
    chart.on('mouseover', function (params) {
      if (params.componentType == 'xAxis') {
        var elementDiv = document.querySelector('#extension');
        var elementStyle =
          'position: absolute;z-index: 99999;color: #fff;font-size: 12px;padding: 5px;display: inline;border-radius: 4px;background-color: #303133;box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 8px';
        elementDiv.style.cssText = elementStyle;
        elementDiv.innerHTML = params.value;
        document.querySelector('html').onmousemove = function (event) {
          var elementDiv = document.querySelector('#extension');
          var xx = event.pageX + 10;
          var yy = event.pageY - 30;
          elementDiv.style.top = yy + 'px';
          elementDiv.style.left = xx + 'px';
        };
      }
    });
    chart.on('mouseout', function (params) {
      if (params.componentType == 'xAxis') {
        var elementDiv = document.querySelector('#extension');
        elementDiv.style.cssText = 'display:none';
      }
    });
  }
  function renderChart() {
    chartInstance = echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
    chartInstance?.setOption(config, true);
    chartInstance?.resize();
    extension(chartInstance);
  }

  return <div id="a" ref={chartRef} style={{ width: '100%', height: '100%' }} />;
}
